package my.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import my.springboot.exception.NotRegisterException;
import my.springboot.po.vo.ReturnCode;
import my.springboot.po.vo.VoData;
import my.springboot.util.ReturnUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;

/**
 * 全局异常处理器
 * @author fengbo
 * @date 2017/9/28
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public VoData methodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
        log.error(" ====== Request url is [{}] ====== ", request.getRequestURL(), e);
        return ReturnUtils.fail(ReturnCode.PARAM_INCOMPLETE);
    }

    @ExceptionHandler(NotRegisterException.class)
    public VoData notRegister(NotRegisterException e) {
        return ReturnUtils.fail(ReturnCode.NOT_REGISTER);
    }

    @ExceptionHandler(ValidationException.class)
    public VoData validationException(HttpServletRequest request, ValidationException e) {
        log.error(" ====== Request url is [{}] ====== ", request.getRequestURL(), e);
        return ReturnUtils.fail(ReturnCode.PARAM_INCOMPLETE);
    }

    @ExceptionHandler(Exception.class)
    public VoData defaultErrorView(HttpServletRequest request, Exception e) {
        log.error(" ====== Request url is [{}] ====== ", request.getRequestURL(), e);
        return ReturnUtils.fail();
    }
}
